﻿using GamFi.API.Application.Contracts.Image.PostUploadImage;
using GamFi.API.Application.Exceptions;
using GamFi.API.Application.Interfaces;
using GamFi.API.Application.Models;
using GamFi.API.Application.Resources;
using MediatR;
using Microsoft.Extensions.Localization;

namespace GamFi.API.Application.Features.Queries.Image.PostUploadImage;

/// <summary>
/// Обработчик для <see cref="PostUploadImageCommand"/>
/// </summary>
public class PostUploadImageCommandHandler(IS3Service s3Service, IDbContext dbContext, IUserContext userContext, IStringLocalizer<ExceptionMessages> localizer)
    : IRequestHandler<PostUploadImageCommand, PostUploadImageResponse>
{
    /// <inheritdoc />
    public async Task<PostUploadImageResponse> Handle(PostUploadImageCommand request,
        CancellationToken cancellationToken)
    {
        if (request is null)
            throw new RequestException(localizer[nameof(RequestException.RequestIsEmpty)]);

        var currentUserId = userContext.CurrentUserId;

        if (currentUserId is null)
            throw new UserException(localizer[nameof(UserException.PermissionDenied)]);

        await using var stream = request.Image.OpenReadStream();
        var address = await s3Service.UploadAsync(
            fileContent: new FileContent
            {
                Content = stream,
                FileName = request.Image.FileName,
                ContentType = request.Image.ContentType
            }, cancellationToken: cancellationToken);

        var imageToSave = new Domain.Entities.Image
        {
            ImageName = request.Image.FileName,
            Address = address,
            Size = request.Image.Length,
            CreatedBy = currentUserId,
            CreatedDate = DateTime.UtcNow,
        };

        await dbContext.Images.AddAsync(imageToSave, cancellationToken);
        await dbContext.SaveChangesAsync(cancellationToken);

        return new PostUploadImageResponse { ImageId = imageToSave.Id };
    }
}